﻿using DataChangeTools.Api.Services;
using DataChangeTools.Utils;
using DataChangeTools.Utils.Constants;
using GeneralUpdate.Common.Download;
using GeneralUpdate.Common.Internal;
using GeneralUpdate.Common.Shared.Object;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataChangeTools.AutoUpdater.ViewModels
{
    public class AutoUpdaterViewModel : BindableBase, IDialogAware
    {
        #region 方法引用
        private readonly IAutoUpdaterService autoUpdaterService;
        private readonly LoggingHelper loggingHelper;
        public AutoUpdaterHelper updaterHelper;
        #endregion

        #region 字段
        private string updateTips;
        public string UpdateTips
        {
            get => updateTips;
            set => SetProperty(ref updateTips, value);
        }


        private string updateVersion;

        public string UpdateVersion
        {
            get { return updateVersion; }
            set => SetProperty(ref updateVersion, value);
        }
        private string updateContent;

        public string UpdateContent
        {
            get { return updateContent; }
            set => SetProperty(ref updateContent, value);
        }
        private string updateBtnContent;

        public string UpdateBtnContent
        {
            get { return updateBtnContent; }
            set => SetProperty(ref updateBtnContent, value);
        }

        private String updateBtnIsEnabled;

        public string UpdateBtnIsEnabled
        {
            get { return updateBtnIsEnabled; }
            set => SetProperty(ref updateBtnIsEnabled, value);
        }
        private string updateContentIsShow;

        public string UpdateContentIsShow
        {
            get { return updateContentIsShow; }
            set => SetProperty(ref updateContentIsShow, value);
        }
        private string upgradeClientVersion;

        public string UpgradeClientVersion
        {
            get { return upgradeClientVersion; }
            set => SetProperty(ref upgradeClientVersion, value);
        }






        #endregion

        #region IDialog方法
        public DialogCloseListener RequestClose { get; set; }
        private ButtonResult result;
        public ButtonResult Result
        {
            get => result;
            set => SetProperty(ref result, value);
        }
        #endregion

        #region 方法
        public DelegateCommand<string> CloseDialogCommand { get; private set; }
        public DelegateCommand<string> UpdateVersionCommand { get; private set; }

        #endregion

        public AutoUpdaterViewModel(IAutoUpdaterService AutoUpdaterService)
        {
            this.autoUpdaterService = AutoUpdaterService;
            this.loggingHelper = new LoggingHelper();
            CloseDialogCommand = new DelegateCommand<string>(CloseDialog);
            UpdateVersionCommand = new DelegateCommand<string>(UpdateVersionFunc);
            InitiUpdate();

        }
        private void InitEvents()
        {
            updaterHelper.MultiDownloadCompletedAction += OnMultiDownloadCompleted;
            updaterHelper.MultiDownloadStatisticsAction += OnMultiDownloadStatistics;
            updaterHelper.OnMultiAllDownloadCompletedAction += OnMultiAllDownloadCompleted;
            updaterHelper.OnMultiDownloadErrorAction += OnMultiDownloadError;
            updaterHelper.OnExceptionAction += OnException;
        }

        public async void InitiUpdate()
        {
            //初始化加载数据
            await GetVersionInfo();
        }


        #region 获取跟新信息
        public async Task GetVersionInfo()
        {
            var todoResult = await autoUpdaterService.GetCheckInfoAsync(ConfigHelper.GetValue("Version"));
            if (todoResult != null && todoResult.Code == 200)
            {
                //版本比较
                UpgradeClientVersion = todoResult.Body.Vserion;
                var ServerVersion = new Version(todoResult.Body.Vserion);

                var LocalVersion = new Version(ConfigHelper.GetValue("Version"));
                if (ServerVersion > LocalVersion)//有新版 提示新版本！
                {
                    UpdateTips = "发现新版本";
                    UpdateContent = todoResult.Body.UpdateInfo;
                    UpdateVersion = "V " + todoResult.Body.Vserion;
                    UpdateBtnContent = "立即更新";
                    UpdateContentIsShow = "Visible";
                    UpdateBtnIsEnabled = "True";//Hidden //Visible
                }
                else if (ServerVersion == LocalVersion) //已经是最新版本，提示
                {
                    UpdateTips = "已是新版本";
                    UpdateContent = todoResult.Body.UpdateInfo;
                    UpdateVersion = "V " + todoResult.Body.Vserion;
                    UpdateBtnContent = "更新";
                    UpdateContentIsShow = "Collapsed";
                    UpdateBtnIsEnabled = "False";//Hidden //Visible
                }
                //updaterHelper.Update();
                //ToDoDtos.Clear();
                //foreach (var item in todoResult.Result.Items)
                //{
                //    ToDoDtos.Add(item);
                //}
            }
        }
        #endregion


        #region 默认方法
        // 关闭弹窗的方法
        private void CloseDialog(string parameter)
        {
            // 根据参数设置弹窗结果

            if (parameter?.ToLower() == "ok")
                result = ButtonResult.OK;
            else if (parameter?.ToLower() == "cancel")
                result = ButtonResult.Cancel;

            // 关闭弹窗
            RequestClose.Invoke(result);
        }


        public bool CanCloseDialog()
        {
            return true; // 允许关闭弹窗
        }

        public void OnDialogClosed()
        {
            // 弹窗关闭时的逻辑

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            // 弹窗打开时的逻辑

            //检测更新

        }
        #endregion


        #region 升级方法

        public void UpdateVersionFunc(string parameter)
        {

            updaterHelper = new AutoUpdaterHelper(AutoUpdaterConstants.BaseUrl, UpgradeClientVersion);
            InitEvents();
            updaterHelper.Update();

            return;
        }

        #endregion


        #region  升级方式实现


        void OnMultiDownloadError(object arg1, MultiDownloadErrorEventArgs arg2)
        {
            var version = arg2.Version as VersionInfo;
            loggingHelper.Writelog($"{version.Version} {arg2.Exception}");
        }

        void OnMultiAllDownloadCompleted(object arg1, MultiAllDownloadCompletedEventArgs arg2)
        {
            //直接Kill当前进程

            //Process.GetCurrentProcess().CloseMainWindow();
            loggingHelper.Writelog(arg2.IsAllDownloadCompleted ? "所有的下载任务已完成！" : $"下载任务已失败！{arg2.FailedVersions.Count}");
        }

        void OnMultiDownloadCompleted(object arg1, MultiDownloadCompletedEventArgs arg2)
        {
            var version = arg2.Version as VersionInfo;

            loggingHelper.Writelog(arg2.IsComplated ? $"当前下载版本：{version.Version}, 下载完成！" : $"当前下载版本：{version.Version}, 下载失败！");
        }

        void OnMultiDownloadStatistics(object arg1, MultiDownloadStatisticsEventArgs arg2)
        {
            var version = arg2.Version as VersionInfo;
            loggingHelper.Writelog($"当前下载版本：{version.Version}，下载速度：{arg2.Speed}，剩余下载时间：{arg2.Remaining}，已下载大小：{arg2.BytesReceived}，总大小：{arg2.TotalBytesToReceive}, 进度百分比：{arg2.ProgressPercentage}%");
        }

        void OnException(object arg1, ExceptionEventArgs arg2)
        {
            loggingHelper.Writelog(JsonConvert.SerializeObject(arg2.Exception));
        }

        #endregion
    }
}
